﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;
using ScaffoldIt.Configuration;

namespace ScaffoldIt
{
    public partial class FormScaffoldItConfigWrapper : UserControl
    {
        private EnvDTE80.DTE2 _dte;

        private FormScaffoldItConfig _cfg;

        public FormScaffoldItConfigWrapper()
        {
            _dte = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE));
            _cfg = new FormScaffoldItConfig();
            _cfg.OnSaveConfig = new FormScaffoldItConfig.SaveConfigHandler(SaveConfig);
            _cfg.OnGetProject = new FormScaffoldItConfig.GetProjectsHandler(GetProjects);
            _cfg.OnOpenFile = new FormScaffoldItConfig.OpenFileHandler(this.Openfile);
            this.Controls.Add(_cfg);
            _cfg.Dock = DockStyle.Fill;

            InitializeComponent();
        }

        void SaveConfig(ScaffoldIt.Configuration.ScaffoldItConfig cfg)
        {
            var item = _dte.Solution.FindProjectItem(cfg.FileName);
            if (item != null)
            {
                var nfo = new FileInfo(cfg.FileName);
                if ((nfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                {
                    bool wasOpened = item.IsOpen;
                    var wnd = item.Open();
                    wnd.Document.Save();
                    if (!wasOpened)
                        wnd.Close();
                }
                //item.Save();
            }
        }

        /// <summary> 
        /// Let this control process the mnemonics.
        /// </summary>
        [UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows)]
        protected override bool ProcessDialogChar(char charCode)
        {
            // If we're the top-level form or control, we need to do the mnemonic handling
            if (charCode != ' ' && ProcessMnemonic(charCode))
            {
                return true;
            }
            return base.ProcessDialogChar(charCode);
        }

        /// <summary>
        /// Enable the IME status handling for this control.
        /// </summary>
        protected override bool CanEnableIme
        {
            get
            {
                return true;
            }
        }

        private string[] GetProjects()
        {
            return _dte.GetAllProjectNames().ToArray();
        }

        private void btnCreateConfig_Click(object sender, EventArgs e)
        {

            string conf = RefreshWindow();

            if (conf == null && !_cfg.HasConfig && _dte.Solution != null && !string.IsNullOrEmpty(_dte.Solution.FileName))
            {
                var cfg = new ScaffoldIt.Configuration.ScaffoldItConfig();
                var solutionFolder = Path.GetDirectoryName(_dte.Solution.FileName);
                cfg.Save(Path.Combine(solutionFolder, "scaffolding.config"));
                _cfg.Init(cfg);
            }

            _dte.GetOrCreateScaffoldItItem();
        }

        public string RefreshWindow()
        {
            var conf = this._dte.ScaffoldingConfigFile();
            if (conf == null && this._cfg.HasConfig)
                this._cfg.Init(null);

           
            if ((conf != null && !this._cfg.HasConfig) || (conf != null && this._cfg.HasConfig && conf != _cfg.ConfigFile))
                Loadconfiguration(conf);

            return conf;
        }

        private void Loadconfiguration(string conf)
        {
            this._cfg.Init(ScaffoldIt.Configuration.ScaffoldItConfig.Load(conf));
        }

        internal void CloseConfig()
        {
            _cfg.Init(null);
        }

        private void btnCreateTemplate_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                var solutionFolder = Path.GetDirectoryName(_dte.Solution.FileName);
                dlg.InitialDirectory = solutionFolder;
                dlg.DefaultExt = "tt";
                dlg.Filter = "T4 template | *.tt";
                if (Directory.Exists(Path.Combine(solutionFolder, "scaffolding")))
                {
                    dlg.InitialDirectory = Path.Combine(solutionFolder, "scaffolding");
                }

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter writer = new StreamWriter(dlg.FileName, false, System.Text.UTF8Encoding.Default))
                    {
                        writer.Write(SampleTemplate.Template());
                    }
                }
            }
        }

        private void Openfile(string filename)
        {
            var solutionFolder = Path.GetDirectoryName(_dte.Solution.FileName);
            var fullpath = Path.Combine(solutionFolder, filename);
            if (File.Exists(fullpath))
            {
                try
                {
                    var wnd = _dte.OpenFile(EnvDTE.Constants.vsViewKindTextView, fullpath);
                    wnd.Activate();
                }
                catch (Exception ex)
                {                    
                }
            }
        }
    }
}
